package com.isesol.seckill.service.impl;

import com.isesol.arch.common.uitil.redis.*;
import org.apache.commons.codec.binary.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.*;

import javax.annotation.*;
import javax.imageio.*;
import java.awt.image.*;
import java.io.*;

/**
 * 图片验证码 Service
 *
 * @author Peter Zhang
 */
@Service
public class CaptchaService {

    @Resource
    RedisUtil redisUtil;

    public BufferedImage getCaptcha(String code, String id,String captchaId) throws Exception {

        String key = "seckill:" + code + ":" + id + "-" + captchaId;
        String str = redisUtil.get(key);

        BufferedImage bufferedImage = ImageIO.read(
                new ByteArrayInputStream(Base64.decodeBase64(str.getBytes())));

        return bufferedImage;

    }

    /**
     * 检查用户输入的安全码是否有效
     *
     * @param codeType     CODE类型
     * @param codeId       CODE ID
     * @param securityCode 需要验证的安全码
     * @return true | false
     */
    public static boolean check(String codeType, String codeId, String securityCode) {

        String key = getKey(codeType, codeId);
//        String value = RedisUtil.get(key);
        String value = "";
        return StringUtils.equals(value, securityCode);
    }

    public static String getKey(String codeType, String codeId) {

        return "seckill:" + codeType + ":" + codeId;
    }

    /**
     * 缓存图片的验证码
     *
     * @param codeType     CODE类型
     * @param codeId       CODE ID，一般用时间戳
     * @param securityCode 需要验证的安全码
     */
    public static void cache(String codeType, String codeId, String securityCode) {

        String key = getKey(codeType, codeId);
        // RedisUtil.set(key, securityCode, 24 * 60 * 60);
    }

    /**
     * 让校验码失效
     *
     * @param codeType CODE类型
     * @param codeId   CODE ID，一般用时间戳
     */
    public static void expire(String codeType, String codeId) {

        String key = getKey(codeType, codeId);
        // RedisUtil.del(key);
    }

}